# Create your views here.
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import Context, loader
from JCUelection.elections.models import *
from django.db.models import Q
from django.core.files import File
from django.contrib.auth.models import User
from django.db import connection
import datetime
from django.views.generic.simple import *
from django.shortcuts import *
from django.forms.models import inlineformset_factory

#year=2009
#month=3
#day=27

global input 
#input = "./facultyMembers.csv"
input= "../facultyMembers.csv"
global output
output = "./facultyMembers.csv"

@login_required
def index(request):
    timeout = 7200
    request.session.set_expiry(timeout)#number is in seconds, confirmed to work correctly
    
    try:
        userID=request.user.__str__()
        facultyMember = FacultyMember.objects.get(bannerId__iexact=userID)
        userSchoolRestriction = facultyMember.department.school
        userDivisionRestriction = facultyMember.department.division
    except:
        if request.user.is_superuser:
            return HttpResponse("This page is not for super users.")
        else:
            return HttpResponse("User not found or no active. Please login as different user if you have not already voted for this election.")
    none='None'
    currentDate = datetime.datetime.today()
    year = currentDate.year
    month = currentDate.month
    day = currentDate.day
    results = ''
    elections = Election.objects.filter(electionDate__lte=currentDate)#during or after startDate
    elections = elections.filter(electionEndDate__gte=currentDate)#before endDate
    elections = elections.order_by('electionEndDate')
    try:
        schoolIssues = elections[0].issue_set.filter(
           Q(schoolRestriction__iexact=userSchoolRestriction) |
           Q(schoolRestriction__iexact=none)
        )
        divisionIssues = schoolIssues.filter(
           Q(divisionRestriction__iexact=userDivisionRestriction) |
           Q(divisionRestriction__iexact=none)
        )
        schoolPositions = elections[0].position_set.filter(
           Q(schoolRestriction__iexact=userSchoolRestriction) |
           Q(schoolRestriction__iexact=none)
        )
        divisionPositions = schoolPositions.filter(
           Q(divisionRestriction__iexact=userDivisionRestriction) |
           Q(divisionRestriction__iexact=none)
        )
        #message = "This will be the user login page. Expires in " + timeout.__str__() + " seconds"
        issuesList = []
        posList = []
        notValid = False
        t = loader.get_template('main_page.html')
        if request.method == 'POST': # If the form has been submitted...
            choicesToSave = []
            posChoicesToSave = []
            #choicesFormset = ChoicesInlineFormSet(request.POST, instance = divisionIssues)
            for thisIssue in divisionIssues:
                voteForm = VoteForm(request.POST,prefix = thisIssue.id,issue=thisIssue)
                issuesList.append(voteForm)
                if voteForm.is_valid():
                    selectedChoice = voteForm.cleaned_data['choices']
                    choicesToSave.append(selectedChoice)
                    #selectedChoice.votes += 1
                    #selectedChoice.save()
                #else:
                    #return HttpResponseRedirect('')
            for thisPos in divisionPositions:
                posForm = PositionForm(request.POST,prefix = thisPos.id,position=thisPos)
                posList.append(posForm)
                try:
                    if posForm.is_valid():
                        selectedChoices = posForm.cleaned_data['candidate']
                        for posChoice in selectedChoices:
                            posChoicesToSave.append(posChoice)
                    else:
                        print "Error in validation"
                        print posForm.errors
                        if(not notValid):
                            notValid = True
                    
                except:
                    return HttpResponse("Error in validation")
                #return HttpResponse(selectedChoices)
            if(notValid):
                c = {
                        'issueDescription_list': divisionIssues,
                        'position_list': posList,
                        'issue_list':issuesList,
                    }
                return render_to_response('main_page.html',c)
            else:
                #save votes
                for selectedChoice in choicesToSave:
                    selectedChoice.votes += 1
                    selectedChoice.save()
                for posChoice in posChoicesToSave:
                    posChoice.votes += 1
                    posChoice.save()
                request.user.is_active = False
                request.user.save()
                return HttpResponseRedirect('/userlogout/') # Redirect after POST
        
        else:
            #unbound forms
            for thisIssue in divisionIssues:
                issuesList.append(VoteForm(prefix=thisIssue.id,issue=thisIssue))
            for thisPos in divisionPositions:
                posList.append(PositionForm(prefix=thisPos.id,position=thisPos))
            
        c = {
                 'issueDescription_list': divisionIssues,
                 'position_list': posList,
                 'issue_list':issuesList,
                 }
        return render_to_response('main_page.html',c)
    except:
        return HttpResponse("There is no election right now.")

@login_required
def activateUsers(request):
    if(request.user.is_superuser):
        import linecache
        import csv
        currentUsers = User.objects.all() #holds all users currently in the database
        inActiveUsers= []
        
        currentRow= 1 #row number the file is currently looking at
        headings= [] #all the headings in the spreadsheet
        employeeData= [] #Each piece of data stored for each employee when employee row in spreadsheet is read.
                     #It is cleared after it is used.
        numFields= 0 #number of fields used in faculty member model
        numberOfRows = 0 #total number of rows in a spreadsheet
        stillReading = True #used to tell if data should be continuously read in
        
        
        
        file = csv.reader(open(input, 'rb')) #opening the file to count the number of rows
        file2 = csv.reader(open(input, 'rb')) #opening the file to read the data
        
        #counts the number of rows in a file
        for row in file: 
            numberOfRows = numberOfRows + 1
        
        #reads the data from each row    
        for row in file2:
            if currentRow==1: #reads in headings for the first row
                for word in row: #adding each heading to the list of headings
                    headings.append(word)
                    numFields= len(headings)
            elif currentRow>2: #reads in the data from each employee
                for word in row: #adds each piece of data to the list of employee data
                    employeeData.append(word)
                if employeeData != [] and stillReading: #executes if there is data to be read in
                    for heading in headings: #saves employee bannerId and active/on leave status in a variable
                        if heading == "BanrID":
                            userName = employeeData[headings.index(heading)]
                        elif heading == "Stat":
                            status= employeeData[headings.index(heading)]
                     
                    #adds inactive users to a list       
                    if status != 'A':
                        user= User.objects.get(username=userName)
                        inActiveUsers.append(user) 
                    
                    #clears the list of employee data    
                    currentIndex=0
                    while currentIndex<numFields:
                        employeeData.pop()
                        currentIndex= currentIndex + 1
                else:
                    stillReading = False
            currentRow= currentRow + 1           
        
        #sets each inactiveUser back to active depending on the spreadsheet
        for user in currentUsers:       
            if(user not in inActiveUsers ):
                user.is_active = True
                user.save()
        return HttpResponse("Activated users")
    else:
       return HttpResponse("Only administrators are allowed to access this page.") 
    
#def results():
#    try:
#        currentDate = datetime.datetime.today()
#        elections = Election.objects.filter(electionDate__lte=currentDate)#during or after startDate
#        elections = elections.filter(electionEndDate__gte=currentDate)#before endDate
#        elections = elections.order_by('electionEndDate')
#    
#        issues = elections[0].issue_set.all()
#        positions = elections[0].position_set.all()
#        c = Context({
#                 'issue_list': issues,
#                 'position_list': positions,
#                 'election': elections[0],
#                 })
#        return c
#    except:
#        return HttpResponse("No active Election currently exists.")
    
@login_required
def allResults(request):
    if(request.user.is_superuser):
        try:
#            currentDate = datetime.datetime.today()
#            elections = Election.objects.filter(electionDate__lte=currentDate)#during or after startDate
#            elections = elections.filter(electionEndDate__gte=currentDate)#before endDate
#            elections = elections.order_by('electionEndDate')
            elections = Election.objects.all()
            issues = Issue.objects.all()
            positions = Position.objects.all()
            c = Context({
                 'issue_list': issues,
                 'position_list': positions,
                 'election_list': elections,
                 })
            t = loader.get_template('results.html')
            return HttpResponse(t.render(c))
        except:
            return HttpResponse("No active Election currently exists.")
        
    else:
        return HttpResponse("Only administrators are allowed to access this page.")

#This function adds data from the facultyMembers.csv file in the application's directory
    #to the facultyMember and User database, displaying any problems or successes on
    #the web-page.
@login_required
def parseCSV(request):
    if(request.user.is_superuser): 
        import linecache
        import csv
            
        #input= "./facultyMembers.csv"
    
        #input= "../facultyMembers.csv"

        currentRow= 1 #row number the file is currently looking at
        currentRecord= 1 #used as a primary key for the faculty member model
        headings= [] #all the headings in the spreadsheet
        employeeData= [] #Each piece of data stored for each employee when employee row in spreadsheet is read.
                     #It is cleared after it is used.
        numFields= 0 #number of fields used in faculty member model
        numberOfRows = 0 #total number of rows in a spreadsheet
        stillReading = True #used to tell if data should be continuously read in
        memberAdded = False #used to tell if a faculty member was added to the FacultyMember,
                        #so the they can be added to the User
        membersNotAdded = [] #will hold information for members not added to the database
        dualDepartment = [] #will hold the information for the members with two departments

        file = csv.reader(open(input, 'rb')) #opening the file to count the number of rows
        file2 = csv.reader(open(input, 'rb')) #opening the file to read the data
    
        currentFacultyMembers = FacultyMember.objects.all() #holds all faculty members currently in the database
        currentUsers = User.objects.all() #holds all users currently in the database
    
        #deletes all of the current faculty members
        for member in currentFacultyMembers:
            member.delete()
    
        #deletes all current users who are not super users    
        for user in currentUsers:
            if user.is_staff != True:
                user.delete()
    
        #counts the number of rows in a file
        for row in file: 
            numberOfRows = numberOfRows + 1
    
        #reads the data from each row    
        for row in file2:
            if currentRow==1: #reads in headings for the first row
                for word in row: #adding each heading to the list of headings
                    headings.append(word)
                    numFields= len(headings)
            elif currentRow>2: #reads in the data from each employee
                for word in row: #adds each piece of data to the list of employee data
                    employeeData.append(word)
                if employeeData != [] and stillReading: #executes if there is data to be read in
                    for heading in headings: #saves each employee data in a variable
                        #stores the data to be used to create the user and/or facultyMember       
                        if heading == "BanrID":
                            userName = employeeData[headings.index(heading)]
                        elif heading == "LNAM":
                            lastName = employeeData[headings.index(heading)]
                        elif heading == "FNAM":
                            firstName = employeeData[headings.index(heading)]
                        elif heading == "MaxDpt":
                            primaryDepartment = employeeData[headings.index(heading)]
                        elif heading == "MinDpt":
                            secondaryDepartment = employeeData[headings.index(heading)]
                        elif heading == "Code":
                            password = employeeData[headings.index(heading)]
                        elif heading == "Stat":
                            status = employeeData[headings.index(heading)]
                        
                    nickname = firstName + " " + lastName
                    
                    #clears the list of employee data    
                    currentIndex=0
                    while currentIndex<numFields:
                        employeeData.pop()
                        currentIndex= currentIndex + 1
                            
                    currentRecord= currentRecord + 1
                    #creating and saving the facultyMember
                    try:
                        #checks for duplicate entries
                        FacultyMember.objects.get(bannerId=userName)
                    except:
                        try: #checks if the department exists before adding the faculty members
                            Department.objects.get(department = primaryDepartment)
                        
                            #adds facultyMembers if they are not already in the database
                            facultyMember = FacultyMember(bannerId = userName, 
                                    lastName = lastName, firstName = firstName,
                                    nickname = nickname, department_id = primaryDepartment)
                            facultyMember.save()
                            if primaryDepartment != secondaryDepartment:
                                membersDualDept = []
                                membersDualDept.append(userName)
                                membersDualDept.append(primaryDepartment)
                                membersDualDept.append(secondaryDepartment)
                                dualDepartment.append(membersDualDept)
                            memberAdded = True
                        except:
                            membersNotAdded.append(userName) #adds the bannerID of faculty member not added
                
                    if memberAdded == True:
                        #creating and saving the user
                        try:
                            #checks for duplicate entries
                            User.objects.get(username=userName)
                        except:
                            #adds users if they are not already in the database
                            user = User.objects.create_user(userName, "" , password)
                            if status != "A":
                                user.is_active = False
                            user.save()
                else:
                    stillReading = False
            memberAdded = False
            currentRow= currentRow + 1
    
        #adds the bannerID's of members who were not added to the database or with dual departments
        errorList = Context({'membersNotAdded': membersNotAdded, 'dualDepartment': dualDepartment})
        template = loader.get_template('parsed_data.html') #gets the template
    
        return HttpResponse(template.render(errorList))
    else:
        return HttpResponse("Only administrators are allowed to access this page.")

#This function creates a page that allows the user to upload any spreadsheet to the 
    #application's directory, and automatically redirects to the parseCSV fuction to 
    #add the data to the database.
@login_required
def inputData(request):
    #where the uploaded file will be stored
    output = input
    #executes if a file has been provided 
    if request.method == 'POST':
        #takes in uploaded form
        uploadForm = UploadDataForm(request.POST, request.FILES)
        #copies file over to directory if it was successfully uploaded
        if uploadForm.is_valid():
            #either creates a new file or deletes the contents of the current file
                #in the directory
            fileOut = open(output, 'wb+')
            #copies the uploaded file to the file in the direcotry
            for chunk in request.FILES['spreadsheet'].chunks():
                fileOut.write(chunk)
            #closes the file when done
            fileOut.close()
            #redirects to parseCSV page if the file was successfully uploaded and
                #added to the directory
            return HttpResponseRedirect('/parsecsv/')
    #executes when page is initially viewed and presents a blank form
    else:
        uploadForm = UploadDataForm()
    #sends the UploadDataForm to the template file_upload.html
    return render_to_response('file_upload.html', {'uploadForm': uploadForm})
